package com.tourism.controller;


import com.tourism.core.common.exception.CustomException;
import com.tourism.core.common.utils.Result;
import com.tourism.domain.dto.role.RoleAuthDTO;
import com.tourism.domain.dto.role.RoleQueryDTO;
import com.tourism.domain.entity.Role;
import com.tourism.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 角色控制器
 *
 * @author lucky
 */
@RequestMapping("/api/admin/role")
@RestController
public class RoleController {

    @Autowired
    private RoleService roleService;

    @PostMapping("page")
    @PreAuthorize("hasAuthority('role:page')")
    public Result<?> getPage(@RequestParam("pageIndex") Integer pageIndex,
                             @RequestParam("pageSize") Integer pageSize,
                             @RequestBody RoleQueryDTO roleQueryDTO) {
        return Result.success(roleService.getPage(pageIndex, pageSize, roleQueryDTO));
    }

    @GetMapping("all")
    @PreAuthorize("hasAuthority('role:all')")
    public Result<List<Role>> getAll() {
        return Result.success(roleService.list());
    }

    @GetMapping("get-auth/{id}")
    @PreAuthorize("hasAuthority('role:get-auth')")
    public Result<List<Long>> getRoleAuth(@PathVariable Long id) {
        return Result.success(roleService.getRoleAuth(id));
    }


    @PostMapping("save-auth")
    @PreAuthorize("hasAuthority('role:save-auth')")
    public Result<Boolean> saveAuth(@RequestBody RoleAuthDTO roleAuthDTO) {
        return roleService.saveAuth(roleAuthDTO) ? Result.success() : Result.failure();
    }

    @PostMapping("save")
    @PreAuthorize("hasAuthority('role:save')")
    public Result<Boolean> save(@RequestBody Role role) {
        return roleService.save(role) ? Result.success() : Result.failure();
    }


    @PutMapping("update")
    @PreAuthorize("hasAuthority('role:update')")
    public Result<Boolean> update(@RequestBody Role role) {
        return roleService.updateById(role) ? Result.success() : Result.failure();
    }

    @DeleteMapping("delete")
    @PreAuthorize("hasAuthority('role:delete')")
    public Result<Boolean> delete(@RequestBody List<Long> ids) {
        if (ids.contains(1L)) {
            throw new CustomException("管理员角色不能删除");
        }
        return roleService.removeBatchByIds(ids) ? Result.success() : Result.failure();
    }
}
